package com.gjy.pd.single;

import java.io.*;
import java.lang.reflect.Constructor;

/**
 * @author 宫静雨
 * @version 1.0
 * @since 2022-12-15 10:35:45
 */
public class SingleTest {

    public static void main(String[] args) throws InterruptedException {
        /*ExecutorService pool = Executors.newFixedThreadPool(1000);
        Set<Integer> set = new HashSet<>();
        for (int i = 0; i < 100000; i++) {
            pool.execute(() -> {
                int hashCode = Single4.getIns().hashCode();
                set.add(hashCode);
            });
        }
        pool.shutdown();

        System.out.println(set);*/

//        reflect();
        Single4 ins = Single4.getIns();
        Object serialize = serialize(ins);
        System.out.println("ins.hashCode() = " + ins.hashCode());
        System.out.println("serialize = " + serialize.hashCode());

        System.out.println("serialize = " + serialize);
        System.out.println("ins = " + ins);

        Runtime.getRuntime()
                .addShutdownHook(new Thread(() -> {
                    System.out.println(Thread.currentThread().getName());
                }));
    }

    private static void reflect() {
        try {
//            Single4 single4 = Single4.class.newInstance();
            Constructor<Single4> constructor = Single4.class.getDeclaredConstructor();
            constructor.setAccessible(true);
            Single4 single4 = constructor.newInstance();
            Single4 ins = Single4.getIns();

            System.out.println("single4.hashCode() = " + single4.hashCode());
            System.out.println("ins.hashCode() = " + ins.hashCode());
        } catch (Exception e) {
            throw new RuntimeException(e);
        }
    }

    private static Object serialize(Object o) {
        try {
            ByteArrayOutputStream baos = new ByteArrayOutputStream();
            ObjectOutputStream oos = new ObjectOutputStream(baos);
            oos.writeObject(o);

            ByteArrayInputStream bais = new ByteArrayInputStream(baos.toByteArray());
            ObjectInputStream ois = new ObjectInputStream(bais);
            return ois.readObject();
        } catch (IOException | ClassNotFoundException e) {
            throw new RuntimeException(e);
        }
    }
}
